package com.qf.device.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.device.entity.Device;
import com.qf.device.entity.DeviceTopic;
import com.qf.device.mapper.DeviceMapper;
import com.qf.device.mapper.DeviceTopicMapper;
import com.qf.device.service.CmdService;
import com.qf.dto.CmdParamDto;
import com.qf.mqttUser.entity.MqttUser;
import com.qf.mqttUser.mapper.MqttUserMapper;
import com.qf.vo.R;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 作者：熊剑
 * 时间：2023/11/1
 * 描述：
 */
@Service
public class CmdServiceImpl implements CmdService {

    @Autowired
    private DeviceTopicMapper deviceTopicMapper;

    @Autowired
    private MqttUserMapper mqttUserMapper;

    @Autowired
    private DeviceMapper deviceMapper;

    @Override
    public R send(CmdParamDto cmdParamDto) throws MqttException {
        //获取设备的topic
        QueryWrapper<DeviceTopic> qw = new QueryWrapper<>();
        qw.lambda().eq(DeviceTopic::getDeviceKey,cmdParamDto.getDeviceKey());
        List<DeviceTopic> deviceTopics = deviceTopicMapper.selectList(qw).stream().filter(item -> item.getTopic().contains("ctrl")).collect(Collectors.toList());

        //发送消息
        //实例化客户端
        int qos = 2;
        String broker = "tcp://43.143.125.148:1883";
        String clientId = "Java的emqx_test";
        MemoryPersistence persistence = new MemoryPersistence();
        MqttClient client = new MqttClient(broker, clientId, persistence);
        QueryWrapper<MqttUser> mqttqw = new QueryWrapper();
        //Tenant tenant = (Tenant) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        QueryWrapper<Device> deviceQueryWrapper = new QueryWrapper<>();
        deviceQueryWrapper.lambda().eq(Device::getDeviceKey,cmdParamDto.getDeviceKey());
        Device device = deviceMapper.selectOne(deviceQueryWrapper);

        mqttqw.lambda().eq(MqttUser::getTenantId,device.getTenantId());
        MqttUser mqttUser = mqttUserMapper.selectOne(mqttqw);
        // MQTT 连接选项
        MqttConnectOptions connOpts = new MqttConnectOptions();

        connOpts.setUserName(mqttUser.getUsername());
        connOpts.setPassword("123456".toCharArray());
        // 保留会话
        connOpts.setCleanSession(true);

        // 建立连接
        client.connect(connOpts);

        //4、发布消息
        String send = JSONUtil.toJsonStr(cmdParamDto);

        MqttMessage message = new MqttMessage(send.getBytes());
        message.setQos(qos);


        client.publish(deviceTopics.get(0).getTopic(),message);

        return R.ok();
    }
}
